import React from "react";
import { Button, Col, Input, Modal, Row, Table, message } from "antd"
import componentTypeList from "./componentTypeList";
import dataTest from "./dataTest";
import EditField from "./editField";
import { DndProvider, DragSourceMonitor, DropTargetMonitor,useDrop } from 'react-dnd';
import { HTML5Backend } from 'react-dnd-html5-backend';
import update from 'immutability-helper';
import { formFieldDelete, formFieldDisabled, formFieldList, formFieldMove } from "@/services/formInteraction";

let dragingIndex = -1;
let dragStartId = ''

class Field extends React.Component{
  constructor(props){
    super(props);
    this.state = {
      loading:false,
      list:[],
      search:""
    }
  }

  componentDidMount(){
    this.getList()
  }

  getList = () => {
    const { location:{query:{id}} } = this.props
    this.setState({
      loading:true
    },async () => {
      const { search } = this.state;
      const res = await formFieldList({search,formId:id})
      this.setState({
        loading:false,
        list:res,
      })
    })
  }

  doSearch = value => {
    this.setState({
      search:value
    },() => {
      this.getList()
    })
  }

  openEdit = id => {
    this.EditField.initModal(id)
  }

  doListMove = async (oldList,newList) => {
    const res = await formFieldMove({sourceFormFieldList:oldList,targetFormFieldList:newList})
    this.getList()
  }

  removeConfirm = id => {
    Modal.confirm({
      title:"确认删除该字典？",
      okText:"确定",
      cancelText:"取消",
      okType:"danger",
      onOk:() => {
        this.doRemove(id)
      }
    })
  }

  doRemove = async id => {
     const res = await formFieldDelete({id})
     message.info(res.message)
     this.getList()
  }

  render(){
    const { list,loading,search } = this.state;
    const { location:{query:{id}} } = this.props
    const columns = [
      {
        title:"序号",
        dataIndex:"index",
        width:80,
        render:(text,row,index) => {
          return index + 1
        }
      },
      {
        title:"字段名称",
        dataIndex:"name",
        width:200,
      },
      {
        title:"字段编码",
        dataIndex:"encoding",
        width:200,
      },
      {
        title:"组件类型",
        dataIndex:"componentType",
        width:100,
        render:type => {
          const index = componentTypeList.findIndex(item => item.typeKey == type);
          return index > -1 ? componentTypeList[index].typeName : ''
        }
      },
      {
        title:"必填",
        dataIndex:"requiredType",
        width:100,
        render:type => {
          return type == 1 ? '必填' : '非必填'
        }
      },
      {
        title:"绑定实体",
        dataIndex:"bindModelName",
        width:200,
      },
      {
        title:"创建人",
        dataIndex:"createUser",
        width:150,
      },
      {
        title:"操作",
        width:150,
        render:(text,row) => {
          return(
            <div>
              <Button type="primary" size="small" onClick={() => this.openEdit(row.id)}>编辑</Button>
              <Button type="danger" size="small" style={{marginLeft:8}} onClick={() => this.removeConfirm(row.id)}>删除</Button>
            </div>
          )
        }
      }
    ]
    const onRow = (record) => ({
      draggable: true,
      style: { cursor: 'move' },
      onDragStart:(ev) => {
        ev.dataTransfer.effectAllowed = 'move'
        dragStartId = record.id
      },
      onDragEnter:(ev) => {
        const nodes = ev.target.parentNode.childNodes
        nodes.forEach((item) => (item.style.borderTop = '2px dashed #1890ff'))
      },
      onDragLeave: (ev) => {
        const nodes = ev.target.parentNode.childNodes
        nodes.forEach((item) => (item.style.borderTop = ''))
      },
      onDrop: (ev) => {
        ev.preventDefault()
        ev.stopPropagation()
        const dropCol = ev.target.tagName !== 'TR' ? ev.target.parentNode : ev.target
        const dropId = record.id
        const dragIndex = list.findIndex((item) => item.id === dragStartId)
        const dropIndex = list.findIndex((item) => item.id === dropId)
        const data = [...list]
        const item = data.splice(dragIndex, 1) // 移除拖动前的元素
        data.splice(dropIndex, 0, item[0]) // 将拖动元素插入到新的位置
        console.log(list,data);
        dropCol.childNodes.forEach((item) => (item.style.borderTop = ''))
        this.doListMove(list,data)
      },
      onDragOver: (ev) => ev.preventDefault()
    })
    return(
      <div>
        <Row style={{marginBottom:24}}>
          <Col span={12}>
            <Input.Search value={search} onChange={(e) => this.setState({search:e.target.value})} placeholder="请输入字段名称/字段编码" onSearch={this.doSearch} style={{width:400}} />
          </Col>
          <Col span={12} style={{textAlign:"right"}}>
            <Button type="primary" onClick={() => this.openEdit()}>创建字段</Button>
          </Col>
        </Row>
        <Table 
          columns={columns}
          dataSource={list}
          loading={loading}
          pagination={false}
          components={this.components}
          onRow={(record) => onRow(record)}
          rowKey={'id'}
        />

        <EditField onRef={ref => this.EditField = ref} formId={id} refreshList={this.getList} />
      </div>
    )
  }
}

export default Field